package com.ebt.m.account.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.account.AccountHttps;
import com.ebt.m.account.json.ValidateCodeCheckRequest;
import com.ebt.m.account.json.ValidateCodeCheckResponse;
import com.ebt.m.account.json.ValidateCodeSendResponse;
import com.ebt.m.account.AccountConstant;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.utils.CountDownManager;
import com.ebt.m.utils.StringUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.BaseActivity;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建时间：2014-11-14 上午10:51:50 项目名称：EBT.assist
 *
 * @author allen.li
 * @version 1.0
 * @since JDK 1.6.0_21 文件名称：ActSendCheckCode.java 类说明：
 */
public class ActForgetPwdChooseContact extends BaseActivity implements OnClickListener {

    @BindView(R.id.return_button)
    ImageView bt_return;
    @BindView(R.id.center_textview)
    TextView tv_title;
    @BindView(R.id.tv_alert_phone)
    TextView tv_alert_phone;

    @BindView(R.id.btn_next)
    Button btn_next;

    @BindView(R.id.btn_getcode)
    Button btn_getcode;

    @BindView(R.id.et_code)
    EditText et_code;


    @BindView(R.id.ll_contact)
    LinearLayout ll_contact;

    private String userName;
    private String phone;
    private static String mValidateId;
    private EBTProgressDialog mProgressDialog;
    private CountDownManager.CountDownListener mCountDownListener;
    private CountDownManager mCountDownManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd_check_code);
        mCountDownManager = CountDownManager.getInstance();
        ButterKnife.bind(this);
        initView();
        initData();
        initProgressDialog();
    }

    public void initView() {
        tv_title.setText(getStr(R.string.find_pwd));
        btn_next.setOnClickListener(this);
        mCountDownListener = new CountDownManager.CountDownListener() {
            @Override
            public void onTick(long remainMillisSecond) {
                int countdownSecond = (int) (remainMillisSecond / 1000);
                updateVCodeHint(String.valueOf(countdownSecond));
            }

            @Override
            public void onFinish() {
                updateVCodeHint("");
            }
        };
        mCountDownManager.setCountDownListener(mCountDownListener);

        et_code.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void afterTextChanged(Editable editable) {
                updateButtonStep0State(editable.toString());
            }
        });
        updateButtonStep0State(et_code.getText().toString().trim());

    }

    private void updateButtonStep0State(String trim) {
        if (TextUtils.isEmpty(trim)) {
            btn_next.setEnabled(false);
        } else {
            btn_next.setEnabled(true);
        }
    }

    private void updateVCodeHint(String countDownHint) {
        if (TextUtils.isEmpty(countDownHint)) {
            btn_getcode.setText("重新发送");
            btn_getcode.setTextColor(getResources().getColor(R.color.btn_green_normal));
            btn_getcode.setEnabled(true);
        } else {
            btn_getcode.setText("重新发送(" + countDownHint + ")");
            btn_getcode.setTextColor(getResources().getColor(R.color.btn_green_disable));
            btn_getcode.setEnabled(false);
        }
    }

    public void initData() {
        Bundle it = getIntent().getExtras();
        userName = it.getString(AccountConstant.USER_NAME);
        phone = it.getString("phone");
        if (phone.length() == 11) {
            String hide = phone.substring(3, 7);
            tv_alert_phone.setText(getString(R.string.send_verification_code, phone.replace(hide, "****")));
        } else {
            tv_alert_phone.setText(getString(R.string.send_verification_code, phone));
        }
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (mCountDownManager.isCountingDown()) {
            initVCodeHintForCountingDown();
            return;
        }
    }

    private void initVCodeHintForCountingDown() {
        btn_getcode.setClickable(true);
        btn_getcode.setText(getStr(R.string.regain));
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_cancel) {
            finish();
        } else if (v.getId() == R.id.btn_next) {
            checkInput();

        }
    }

    private void checkInput() {
        String inputCode = et_code.getText().toString().trim();

        //校对验证码
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }

        if (TextUtils.isEmpty(mValidateId)) {
            ToastUtil.showToast("验证码无效，请重新获取");
            return;
        }

        //校验验证码
        showProgress("正在校验验证码");
        ValidateCodeCheckRequest request = new ValidateCodeCheckRequest(phone,
                mValidateId,
                inputCode);
        EBTAPI mApi = AppInitService.getEbtApi();
        mApi.checkValidateCode(request)
                .compose(RxUtil.rxTransformer(this))
                .subscribe(checkResult -> {
                    hideProgress();
                    ValidateCodeCheckResponse validateCodeCheckResponse = checkResult.getData();
                    if (validateCodeCheckResponse.isSuccess) {
                        UIHelper.hideSoftInputFromWindow(this);
                        Bundle b = new Bundle();
                        b.putString(AccountConstant.USER_ID, "");
                        b.putString(AccountConstant.USER_NAME, userName);
                        b.putString(AccountConstant.USER_PHONE, phone);
                        gotoActivity(ActResetPwd.class, b);
                    } else {
                        com.ebt.m.commons.utils.ToastUtil.show(this, "验证码校验失败");
                    }
                }, throwable -> {
                    hideProgress();
                    NetUtils.checkHttpException(this, throwable);
                });
    }

    @OnClick(R.id.btn_getcode)
    public void sendCode(View v) {
        if (!StringUtils.isEmpty(phone)) {
            showProgress("正在获取验证码...");
            mCountDownManager.startCountDown();
            //发送验证码
            AccountHttps.getInstance().sendValidateCode(
                    phone,
                    getSendVCodeSubscriber(), this);
        } else {
            toast("未获取到绑定手机号。");
        }
    }

    //发送验证码
    private Observer getSendVCodeSubscriber() {
        return new Observer<BaseDataResult<ValidateCodeSendResponse>>() {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtils.checkHttpException(ActForgetPwdChooseContact.this, e);
                hideProgress();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<ValidateCodeSendResponse> responseJson) {
                hideProgress();
                if (responseJson == null || responseJson.getData() == null) {
                    ToastUtil.showSendVCodeErrorMessage(responseJson);
                    return;
                }
                if (responseJson.getData() != null) {
                    ValidateCodeSendResponse validateCodeSendResponse = responseJson.getData();
                    if (validateCodeSendResponse.isSuccess) {
                        mValidateId = validateCodeSendResponse.getValidateId();
                        showSendResultOk();
                    } else {
                        ToastUtil.showSendVCodeErrorMessage(responseJson);
                    }
                }
            }
        };
    }

    private void showSendResultOk() {
        if (!StringUtils.isEmpty(phone)) {
            StringBuffer alert = new StringBuffer(
                    "验证码已经发送到您");
            if (phone.length() == 11) {
                String hide = phone.substring(3,
                        7);
                alert.append(phone.replace(hide,
                        "****"));
            } else {
                alert.append(phone);
            }
            alert.append("的手机上");
            toast(alert.toString());
        }
    }

    @OnClick(R.id.return_button)
    void cancle(View v) {
        finish();
    }


    private void initProgressDialog() {
        mProgressDialog = new EBTProgressDialog(this);
    }

    private void showProgress(String message) {
        if (mProgressDialog != null && !mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(message);
            mProgressDialog.show();
        }
    }

    private void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
}
